﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using ZR.Admin.WebApi.Filters;
using ZR.Model.Dto.Business.ProductionControl;
using ZR.Model.System;
using ZR.Service.IService.ProductionControl;
using ZR.Service.Service.ProductionControl;

namespace CKS.MES.Server.Controllers.Business.ProductionControl
{
    /// <summary>
    /// 三坐标服务
    /// </summary>
    [Verify]
    [Route("business/CksCMMDetail")]
    [ApiExplorerSettings(GroupName = "business")]
    public class CksCMMDetailController : BaseController
    {
        private readonly ICksCMMService _cksCMMService;
        private readonly ICksCMMItemService _cksCMMItemService;
        private readonly ICksCMMParameterService _cksCMMParameterService;
        private readonly ISysDictDataService _sysDictDataService;

        public CksCMMDetailController(ISysDictDataService sysDictDataService,ICksCMMService cksCMMService, ICksCMMItemService cksCMMItemService, ICksCMMParameterService cksCMMParameterService)
        {
            _sysDictDataService = sysDictDataService;
            _cksCMMService = cksCMMService;
            _cksCMMItemService = cksCMMItemService;
            _cksCMMParameterService = cksCMMParameterService;
        }

        /// <summary>
        /// 查询三坐标数据列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "cmmrecord:list")]
        public IActionResult QueryList([FromQuery] CksCMMDetailQueryDto parm)
        {
            var response = _cksCMMService.GetList(parm);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询三坐标数据参数列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost("paramlist")]
        public IActionResult QueryCksParamList([FromBody] CksCMMParamQueryDto param)
        {
            var response = _cksCMMParameterService.GetList(param);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询三坐标数据集合列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost("itemList")]
        public IActionResult QueryCksItemList([FromBody] CksCMMParamQueryDto param)
        {
            var response = _cksCMMItemService.GetList(param);
            return SUCCESS(response);
        }
        string _sharedBasePath = "";

        [HttpPost("open")]
        public IActionResult OpenPdf([FromBody] PdfQueryDto request)
        {
           var info= _cksCMMService.GetInfo(request.Id);
            var deviceApiInfo = _sysDictDataService.Queryable().Where(x=>x.DictLabel==info.F1).First();
            if (deviceApiInfo==null)
            {
                return BadRequest("未找到当前产品所属设备");
            }
            try
            {
                string ip = ExtractIpAddress(deviceApiInfo.DictValue);
                var fullPath = $@"\\{ip}\ProductFile\{DateTime.Now:yyyyMMdd}\{info.ProductId}.pdf";
                if (!fullPath.StartsWith(_sharedBasePath, StringComparison.OrdinalIgnoreCase))
                {
                    return Forbid("无权限访问该路径");
                }
                if (!System.IO.File.Exists(fullPath))
                {
                    return NotFound("文件不存在");
                }
                if (Path.GetExtension(fullPath).ToLower() != ".pdf")
                {
                    return BadRequest("文件不是 PDF 格式");
                }
                var fileStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read);
                return File(fileStream, "application/pdf", enableRangeProcessing: true);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"服务器错误：{ex.Message}");
            }
        }
        private string ExtractIpAddress(string url)
        {
            if (!Uri.TryCreate(url, UriKind.Absolute, out Uri parsedUri))
            {
                return null; // URL 格式无效
            }
            string host = parsedUri.Host;
            if (host=="localhost")
            {
                host = "127.0.0.1";
            }
            if (IPAddress.TryParse(host, out IPAddress ipAddress))
            {
                return ipAddress.ToString();
            }

            return null;
        }
    }
}